/*
		ServEngine framework library
		A library to fast develop JEE online applications
	
		Copyright 2008 José Ignacio de Córdoba Álvaro

		Licensed under the Apache License, Version 2.0 (the "License");
		you may not use this file except in compliance with the License.
		You may obtain a copy of the License at

				http://www.apache.org/licenses/LICENSE-2.0

		Unless required by applicable law or agreed to in writing, software
		distributed under the License is distributed on an "AS IS" BASIS,
		WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
		See the License for the specific language governing permissions and
		limitations under the License.
	
		Jose Ignacio de Cordoba Alvaro
		http://ignacio.decordoba.com
*/

package com.servengine.entry;

import com.servengine.image.ThumbnailUtils;
import com.servengine.user.UnidentifiedUserException;
import com.servengine.user.UserSessionSBean;

import java.awt.Dimension;
import java.awt.Image;
import java.awt.image.BufferedImage;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import java.util.Collection;
import java.util.List;

import javax.mail.internet.InternetAddress;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public abstract class EntryActions extends com.servengine.struts.ClientAction
{
	private static org.apache.commons.logging.Log log=org.apache.commons.logging.LogFactory.getLog(EntryActions.class.getName());
	protected EntryManagerLocal entryManager;

	public void initAction(javax.naming.Context context)
	{
		try
		{
			entryManager=(EntryManagerLocal)context.lookup("EntryManager/local");
		} catch (Exception e)
		{
			log.error(e.getMessage(), e);
			throw new IllegalStateException(e.getMessage());
		}
		//		log.info(getClass().getName() + " initialized"); //se supone que esta clase siempre se sobrecarga.
	}

	public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
			UserSessionSBean userSession=getUserSession(request);
			EntryActionForm entryForm=(EntryActionForm)form;
			Entry entry = entryManager.getEntry(userSession.getPortalid(), entryForm.getId());
			PropertyUtils.copyProperties(entryForm, entry);
		  request.setAttribute("entry",entry);
			return mapping.findForward("success");
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
			saveErrors(request, getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}

	public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
	  UserSessionSBean userSession=getUserSession(request);
	  if (userSession.isGuest())
			throw new UnidentifiedUserException();
//	    return mapping.findForward("loginform");
		try
		{
			EntryActionForm entryForm=(EntryActionForm)form;
			if (!userSession.isGuest())
			{
				entryForm.setUserName(userSession.getUser().getName());
				entryForm.setUserid(userSession.getUser().getUserid());
			  entryForm.setUserId(userSession.getUser().getId());
			}
			return mapping.findForward("success");
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
			saveErrors(request, getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}

	public ActionForward store(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
			UserSessionSBean userSession=getUserSession(request);
			if (userSession.isGuest())
				return mapping.findForward("loginform");
			EntryActionForm entryForm=(EntryActionForm)form;
			Entry entry=entryForm.getId()==null?new Entry(usermanager.getUser(userSession.getPortalid(), userSession.getUser().getId()), entryForm.getEmail(), entryForm.getUserName(), getModule(), getItemType(), entryForm.getItemId(), entryForm.isPrivateEntry()):entryManager.getEntry(userSession.getPortalid(), entryForm.getId());
			if (!entry.getUser().getId().equals(userSession.getUser().getId()))
				throw new IllegalArgumentException();
			PropertyUtils.copyProperties(entry, entryForm); //Hacemos esto por que el formulario no tiene userId ni nada mas.
			if (entry.getId()==null)
				entryManager.persist(entry); //String portalid, Integer userId, String module, String action, String method, String data, String ipaddress
			logManager.log(userSession.getPortalid(), userSession.getUser().getId(), "entry", "EntryActions", "store", entry.getBody(), request.getRemoteAddr());
			// Store Picture
			if (entryForm.getPictureFile()!=null&&entryForm.getPictureFile().getFileSize()>0)
			{
				Image picture=ThumbnailUtils.JPEGtoImage(entryForm.getPictureFile().getInputStream());
				if (picture.getWidth(null)>320||picture.getHeight(null)>240) //TODO poner esto como parámetro de aplicación
				{
					BufferedImage bufferedImage=ThumbnailUtils.getScaledimage(picture, new Dimension(320, 240));
					ByteArrayOutputStream byteOutputStream=new ByteArrayOutputStream();
					ThumbnailUtils.writeJPG(bufferedImage, byteOutputStream, (float)0.5);
				} else
					entry.setPicture(entryForm.getPictureFile().getFileData());
			}
			if (entryForm.getId()==null&&entry.getUser()!=null&&entry.getUser().getEmail()!=null)
				try
				{
					request.setAttribute("title", entryForm.getTitle());
					request.setAttribute("comment", entryForm.getBody());
					InternetAddress portalemail=portalmanager.getEmail(userSession.getPortalid()); // Resolver lo del correo
					String html=getServletContextUtils().getResourceAsString(userSession.getUser(), request, response, "/user/"+getModule()+"_"+getItemType()+"_Message.jsp");
					getMailRelay().send(portalemail.getAddress(), entry.getUser().getEmail(), "New entry", null, html);
				} catch (Throwable e)
				{
				  if (log.isDebugEnabled())
				    log.error(e.getMessage(),e);
				  else
				    log.error(e.getMessage());
				}
			entryForm.setId(entry.getId());
			return unspecified(mapping, form, request, response);
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
			saveErrors(request, getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}

	protected abstract String getModule(); // TODO ¿Cogerlo automáticamente del paquete?

	protected abstract String getItemType();

	public ActionForward remove(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
			UserSessionSBean userSession=getUserSession(request);
			if (userSession.isGuest())
				return mapping.findForward("loginform");
			EntryActionForm entryForm=(EntryActionForm)form;
			Entry entry=entryManager.getEntry(getUserSession(request).getPortalid(), entryForm.getId());
			if (!userSession.isAdmin()&&!entry.getUser().getId().equals(userSession.getUser().getId()))
				throw new IllegalArgumentException();
			entryManager.removeEntry(userSession.getPortalid(), entry.getId());
			logManager.log(userSession.getPortalid(), userSession.getUser().getId(), "entry", "EntryActions", "remove", ""+entry.getId(), request.getRemoteAddr());
			/*		  File file = getPictureFile(userSession.getPortalid(),entryForm.getPkey());
			if (file.exists())
				file.delete();*/
			response.sendRedirect(request.getParameter("forward")==null?request.getHeader("Referer"):request.getParameter("forward"));
			return null;
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
			saveErrors(request, getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}

	public ActionForward entries(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
			UserSessionSBean userSession=getUserSession(request);
			EntryActionForm entryForm=(EntryActionForm)form;
			Collection<Entry> entries=entryManager.getEntries(userSession.getPortalid(), getModule(), getItemType(), entryForm.getItemId());
			/*			for (Entry entry: entries)
				entry.setHasPicture(getPictureFile(userSession.getPortalid(),entry.getPkey()).exists());*/
			request.getSession().setAttribute(getModule()+"_"+getItemType()+"_entries", entries);
			return mapping.findForward("entries");
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
			saveErrors(request, getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}

	public ActionForward myEntries(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
			UserSessionSBean userSession=getUserSession(request);
			List<Entry> entries=entryManager.getUserEntries(getModule(), getItemType(), userSession.getUser());
			request.getSession().setAttribute(getModule()+"_"+getItemType()+"_myEntries", entries);
			return mapping.findForward("myEntries");
		} catch (Throwable e)
		{
			log.error(e.getMessage(), e);
			saveErrors(request, getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}
}
